package com.heima.user.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author lyd
 * @since 2022-06-20
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    IApUserFollowService userFollowService;     //app用户关注信息表

    /*
        app端用户登录
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //关键数据校验
        if (dto == null || (StringUtils.isEmpty(dto.getEquipmentId()))&&StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPhone())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断用户状态
        //若密码  电话号码存在则是正常登录
        if (!StringUtils.isEmpty(dto.getPassword())&&!StringUtils.isEmpty(dto.getPhone())){
            //根据电话号码查询用户
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone,dto.getPhone());
            ApUser one = this.getOne(query);

            //不存在提示用户不存在
            if (one == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //存在 取出用户的salt
            String salt = one.getSalt();
            //获取用户输入的密码
            String pwd = dto.getPassword();
            //拼接两部分
            String password = pwd + salt;

            //采用md5加密
            String md5 = DigestUtils.md5DigestAsHex(password.getBytes());

            //对比数据库中存储的密码
            //如果不一致 提示密码错误
            if (!md5.equals(one.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //一致  使用jwt生成token
            Map<String,Object> userinfo = new HashMap<>();
            userinfo.put("userId",one.getId());
            String token = AppJwtUtil.getToken(userinfo);

            //返回给前端
            ApUser adUser = new ApUser();
            adUser.setName(one.getName());
            Map<String,Object> map = new HashMap<>();
            map.put("user",adUser);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

        //若设备id存在则是游客登陆
        if (!StringUtils.isEmpty(dto.getEquipmentId())){
            Map<String,Object> userinfo = new HashMap<>();
            userinfo.put("userId",0);
            String token = AppJwtUtil.getToken(userinfo);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    /*
        app端用户关注取消关注行为
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //构建关注对象
        ApUserFollow userFollow = new ApUserFollow();
        //从本地线程中获取用户id
        User user = AppThreadUtil.getThread();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        userFollow.setUserId(user.getUserId());     //用户ID
        ApUser apUser = this.getById(user.getUserId());
        userFollow.setUserName(apUser.getName());   //用户昵称
        //调用articleFeign查询作者id  作者姓名
        ResponseResult<ApAuthor> authorResponseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (authorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApAuthor author = authorResponseResult.getData();
            userFollow.setFollowId(author.getUserId());
            userFollow.setFollowName(author.getName());
        }
        userFollow.setLevel(1);     //关注度
        userFollow.setCreatedTime(new Date());  //创建时间

        //判断当前用户是否与已经关注过该作者
        LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
        //根据当前用户查询
        query.eq(ApUserFollow::getUserId,userFollow.getUserId());
        //根据关注作者查询
        query.eq(ApUserFollow::getFollowId,userFollow.getFollowId());
        ApUserFollow one = userFollowService.getOne(query);
        //如果为空新增
        if (one == null){
            //判断是否是关注行为
            if (dto.getOperation() == 0){
                userFollowService.save(userFollow);
            }
        }else {
            //不为空  判断用户行为 如果是取消点赞   删除对应记录
            if (dto.getOperation() == 1){
                //根据查询条件删除记录
                userFollowService.remove(query);
            }
        }
        return ResponseResult.okResult();
    }
}
